#include "Share.hpp"
#include <vector>
#include "Logger.hpp"

#define LINE_SIZE 1024

//初始化Log
Logger& Log = Logger::GetInstance();

enum{
    LISTENING_NORMAL = 1,
    LISTENING_CLOSE = 0,
    LISTENING_ERR = -1
};

//C风格-监听信息
int ListeningCType(int &fd){
    char line[LINE_SIZE] = {0};
    int bytes_read = read(fd, line, sizeof(line));
    
    if(bytes_read > 0){
        line[bytes_read] = '\0';
        std::cout << "Client say: " << line;
        return LISTENING_NORMAL;
    }
    else if(bytes_read == 0){
        //TODO
        return LISTENING_CLOSE;
    }else{
        return LISTENING_ERR;
    }
}

//C++风格-监听信息
int ListeningCPPType(int &fd){
    std::vector<char> Buffer(1024);

    ssize_t bytes_read = read(fd, Buffer.data(), Buffer.size());
    
    std::string line;
    if(bytes_read > 0){
        line.assign(Buffer.data(), bytes_read);
        std::cout << "Client say: " << line << std::endl;

        //测试Log
        Log.SetOutputWay(SINGAL_FILE);
        Log(Debug, "这是一个测试", line.c_str());

        return LISTENING_NORMAL;
    }
    else if(bytes_read == 0){
        //TODO
        return LISTENING_CLOSE;
    }else{
        return LISTENING_ERR;
    }
}

//服务端管理命名管道
int main(){
    //初始化开始-创建管道
    Initialization Init;

    //测试Log
    Log.SetOutputWay(SCREEN);
    Log(Debug, "这是一个测试:666");

    //测试Log
    Log.SetOutputWay(MULTIPLE_FILES);
    Log(Debug, "这是一个测试:666");
    Log(Info, "这是一个测试:666");
    Log(Warning, "这是一个测试:666");
    Log(Error, "这是一个测试:666");
    Log(Fatal, "这是一个测试:666");

    //打开管道-读
    int open_ret = open(NAMEDPIPE_PATH, O_RDONLY);
    //检查打开情况
    if(open_ret == -1){
        perror("Failed to open");
        exit(FILE_OPEN_READ_ERR);
    }

    //进入循环读取信息
    while(true){
        // int listen_ret = ListeningCType(open_ret);
        int listen_ret = ListeningCPPType(open_ret);

        if(listen_ret == LISTENING_CLOSE || listen_ret == LISTENING_ERR){//写端关闭 或 出现意外
            break;
        }
    }

    close(open_ret);//关闭读端
}